package LocalServerThreads;

import generalClasses.PingMachine;
import generalClasses.ProgramData;
import generalClasses.Server;
import LocalServerProtocols.AuthenticateLocalServer;
import LocalServerTcp.TcpClient;

public class RegistrationThread extends Thread
{
	private Server _currentServer;
	private static String GATEWAY_DOWN = "There is a problem with your network connection"; 
	
	public RegistrationThread(Server server)
	{
		super( server.getAdress() + " registration thread" );
		_currentServer = server;
	}

	/* (non-Javadoc)
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run()
	{
		while ( true )
		{
			//create an authenticateProtocol 
			AuthenticateLocalServer authenticateProtocol = new AuthenticateLocalServer( _currentServer );
			//Try to create TCP connection 
			TcpClient tcpClient = new TcpClient("none");

			//there is no connection with MAIN server and BACKUP server  
			if ( tcpClient.isConnected() == false )
			{
				//there is no connection do  default gateway
				if ( PingMachine.callGateway() == false )
				{
					System.err.println( GATEWAY_DOWN );
				}
				//Both Main and Backup servers are down 
				else
				{
					System.err.println("Both Main server and backup server are down");
					System.err.println("Start this server again when one of them will run");
					System.exit(1);
				}
			}
			//there is a connection with a server, try to register it
			tcpClient.run( authenticateProtocol, authenticateProtocol.get_protocolAction() );
			
			try
			{
				Thread.sleep( ProgramData.ONE_MINUTE );
			}
			catch (InterruptedException e)
			{
				System.err.println(this.getClass().getSimpleName() + " " + _currentServer.getAdress()+ " Failed to sleep in thread");
			}
		}
	}

}
